package com.liy.framework.common.office.pdf;

import com.jacob.activeX.*;
import com.jacob.com.*;
import java.io.*;
import org.slf4j.*;

public class Word2PdfUtil
{
    protected static Logger log;
    static final int wdDoNotSaveChanges = 0;
    static final int wdFormatPDF = 17;
    
    public static boolean word2pdf(final String source, final String target) throws Exception {
        Word2PdfUtil.log.info("Word\u8f6cPDF\u5f00\u59cb\u542f\u52a8...");
        final long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        try {
            app = new ActiveXComponent("Word.Application");
            app.setProperty("Visible", false);
            final Dispatch docs = app.getProperty("Documents").toDispatch();
            Word2PdfUtil.log.info("\u6253\u5f00\u6587\u6863\uff1a" + source);
            final Dispatch doc = Dispatch.call(docs, "Open", new Object[] { source, false, true }).toDispatch();
            Word2PdfUtil.log.info("\u8f6c\u6362\u6587\u6863\u5230PDF\uff1a" + target);
            final File tofile = new File(target);
            if (!tofile.getParentFile().exists()) {
                tofile.getParentFile().mkdirs();
            }
            if (tofile.exists()) {
                tofile.delete();
            }
            Dispatch.call(doc, "SaveAs", new Object[] { target, 17 });
            Dispatch.call(doc, "Close", new Object[] { false });
            final long end = System.currentTimeMillis();
            Word2PdfUtil.log.info("\u8f6c\u6362\u5b8c\u6210\uff0c\u7528\u65f6\uff1a" + (end - start) + "ms");
            return true;
        }
        catch (Exception e) {
            Word2PdfUtil.log.info(source + ">>>>Word\u8f6cPDF\u51fa\u9519\uff1a" + e.getMessage());
            throw new Exception("Word\u8f6cPDF\u51fa\u9519\uff1a" + e.getMessage(), e);
        }
        finally {
            if (app != null) {
                app.invoke("Quit", 0);
            }
        }
    }
    
    public static void main(final String[] args) {
        try {
            word2pdf("C:\\Temp\\xml\\abc.doc", "C:\\Temp\\xml\\abc.pdf");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    static {
        Word2PdfUtil.log = LoggerFactory.getLogger((Class)Word2PdfUtil.class);
    }
}
